package com.yueya.common.city.service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yueya.common.city.model.City;
import com.yueya.common.model.Tree;

public class CityService {
	
	public List<Tree> getListByParentId(int parent_id){
		List<Tree>  listTree =new ArrayList<Tree>();
		List<City> list = City.dao.find("select * from w_city where parent_id = ?",parent_id);
	    Iterator<City> it =	list.iterator();
	    Tree tree =null;
	    City city = null;
	    while(it.hasNext()){
	    	 city=it.next();
	    	 tree= new Tree();
	    	 tree.setId(city.getInt("id").toString());
	    	 tree.setText(city.getStr("name"));
	    	 tree.setPid(city.getInt("parent_id").toString());
	    	 tree.setAttributes(city);
	    	
	    	 List<Tree> childrens =getSimListByParentId(city.getInt("id"));
	    	 if(childrens.size()>0){
	    		 tree.setState("closed");
	    	 }
	    	 listTree.add(tree);
	    	
	    }
		return listTree;
		
	}
	
	public List<Tree> getSimListByParentId(int parent_id){
		List<Tree>  listTree =new ArrayList<Tree>();
		List<City> list = City.dao.find("select * from w_city where parent_id = ?",parent_id);
	    Iterator<City> it =	list.iterator();
	    Tree tree =null;
	    City city = null;
	    while(it.hasNext()){
	    	 city=it.next();
	    	 tree= new Tree();
	    	 tree.setId(city.getInt("id").toString());
	    	 tree.setText(city.getStr("name"));
	    	 tree.setPid(city.getInt("parent_id").toString());
	    	 listTree.add(tree);
	    	
	    }
		return listTree;
		
	}
	
	
	@SuppressWarnings("rawtypes")
	public Page pagination (int pageNumber ,int pageSize,Map<String,String> map){
		String select  ="SELECT a.*,(select name from w_city where id =a.parent_id ) parent_name ";
		StringBuffer sb = new StringBuffer();
		sb.append(" FROM w_city a ");
		sb.append(" WHERE 1=1 ");
		if(StrKit.notBlank(map.get("pid"))){
			sb.append(" AND a.parent_id = '"+map.get("pid")+"' " );
		}
		if(StrKit.notBlank(map.get("name"))){
			sb.append(" AND a.name like '%"+map.get("name")+"%' " );
		}
		
		
		String sqlExceptSelect =sb.toString();
		System.out.println("sql "+select+sqlExceptSelect);
		Page page = City.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
		return page;
	}
	
	@SuppressWarnings("rawtypes")
	public List getListByLevel(int level){
		List list = City.dao.find("select id, name from w_city where level =?",level-1<0?0:level-1);
		return list;
		
	}
	
	public int getMaxId(){
		return City.dao.findFirst("select Max(id) mx from w_city ").getInt("mx");
	}
	
	@Before(Tx.class)
	public void setDoMain(String id ,String domain){
	  String sql ="update w_city set domain=? where id=?";
      Db.update(sql,domain,id);
	}
	
	public void domain(String parent_id){
		  String sql ="select * from w_city where parent_id=?";
	      @SuppressWarnings("rawtypes")
		List list = Db.find(sql,parent_id);
	      Record parent = Db.findById("w_city", parent_id);
	      String domainStr ="";
	      if(StrKit.notNull(parent)){
	    	  domainStr=parent.getStr("domain");
	      }else{
	    	  domainStr ="";
	      }
	     @SuppressWarnings("unchecked")
		Iterator<Record> it = list.iterator();
	     while(it.hasNext()){
	    	 
	    	 Record record = it.next();
             if(record.getInt("id")>22){
	    	 String id = record.getInt("id").toString();
	    	 String domain=domainStr+"|"+id;
	    	 System.out.println("domain:"+domain.trim());
	    	 setDoMain(id , domain.trim());
	    	 domain(id);
	    	 }
	     }
		
	}
	
	/**
	 * 0 1省 2 市 3 区县 
	 * @param name
	 * @param level
	 * @return
	 */
	public List<City> getListByName(String name,int level){
		String sql="select * from w_city where (name like '%"+name+"%' or domain like  '"+name+"%') and level<= ?";
		List<City> list =City.dao.find(sql,level);
		return list;	
	}
	
	
	@SuppressWarnings("unchecked")
	public List<Record> getListByNameRecord(String name,int level){
		String sql="select * from w_city where  (name like '%"+name+"%' or domain like  '"+name+"%')  and level<= ? ";
		List<Record> list =Db.find(sql,level);
		@SuppressWarnings("rawtypes")
		List<Record> liststr=new ArrayList();
	    for(int i=0 ;i<list.size();i++){
	    	Record record =list.get(i);
	    	String domainstr= record.get("domain");
	    	if(StrKit.notBlank(domainstr)){
	    		String[] domains=domainstr.split("\\|");
	    		String regine="";
	    		for(int j=1;j<domains.length;j++){
	    			System.out.println(domains[j]);
	    			regine+=City.dao.findById(domains[j]).getStr("name");
	    		}
	    		
	    		System.out.println(regine);
	    		record.set("regine", regine);
	    	}
	    	
	    	liststr.add(i,record);
	    }
		
		return liststr;
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void wirteTxt(){
	
		 //List<Record> list = Db.find("select id,name,longitude log ,latitude lat  from w_city  where level=1 and city=1 ");
		 List<Record> list = Db.find("select * from w_city where parent_id = 325");
		 List<Record> rets =new ArrayList();
		 Iterator<Record> it = list.iterator();
		
		while(it.hasNext()){
			Record record =it.next();
			record.set("sub", getSubList(record.getInt("id").toString()));
			rets.add(record);
	
		}
		System.out.println(JsonKit.toJson(list));
		
		TextToFile("F:\\city.txt",JsonKit.toJson(list));
	};


	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Record> getSubList(String parent_id){
		List<Record> rets = new ArrayList();
		String sql="select id,name,longitude log ,latitude lat  from w_city  where parent_id=? and   level<3   " ;
		List<Record> list = Db.find(sql,parent_id);
        Iterator<Record> it = list.iterator();
		
		while(it.hasNext()){
			Record record =it.next();
			 System.out.println("-----id"+record.getInt("id")+"--name"+record.getStr("name")+"--------");
			record.set("sub", getSubList(record.getInt("id").toString()));
			rets.add(record);
		
		}
		
		return rets;
	}
	
	
	
	
	public void TextToFile(final String strFilename, final String strBuffer)  
	  {  
	    try  
	    {      
	      // 创建文件对象  
	      File fileText = new File(strFilename);  
	      // 向文件写入对象写入信息  
	      FileWriter fileWriter = new FileWriter(fileText);  
	  
	      // 写文件        
	      fileWriter.write(strBuffer);  
	      // 关闭  
	      fileWriter.close();  
	    }  
	    catch (IOException e)  
	    {  
	      //  
	      e.printStackTrace();  
	    }  
	  }
	
	/**
	 * 将中文地名解析为id形式
	 * @param address
	 * @return
	 * @author 李毅杰
	 * @time：2017年8月30日 下午4:47:21
	 */
	public String parse(String address){
		if(StrKit.isBlank(address))	return null;
		String domain = null;
		String[] ss = address.split("-");
		String s = null;
		
		int parent = 0;
		int level = 1;
		for(int i=0; i<ss.length; i++){
			s = ss[i];
			City city = City.dao.findByNameAndLevel(s, level, parent);
			//开头为市的情况
			if(null==city && 0==i){
				city = City.dao.findByNameAndLevel(s, level+1);
				if(null != city){
					 level++;
				}else{
					return null;
				}
			}
			
			if(null != city){
				domain = city.getStr("domain");
				parent = city.getInt("id");
			}
			level++;
		}
		
		return domain;
	}
	
}
